import React, { Component,Fragment } from 'react';
import {Table,Button,Icon,Form,Input,Card,Modal,message,Popconfirm,Tree,Transfer} from 'antd';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {PAGE_SIZE} from './constants';
const ENTITY = 'role';
//dva-loading
export default  @connect(state=>(
  {...state[ENTITY],loading:state.loading.models[ENTITY]}
)) class componentName extends Component {
  save = (payload)=>{
    this.props.dispatch({
      type:`${ENTITY}/save`,
      payload
    });
  }
  onAdd = ()=>{
    this.save({editVisible:true});
  }
  onEditCancel = ()=>{
    this.save({editVisible:false});
  }
  onEditOk = ()=>{
    this.editForm.props.form.validateFields((err,payload)=>{
      if(err){
        message.error(err);
      }else{
        this.props.dispatch({
          type:this.props.isCreate?`${ENTITY}/create`:`${ENTITY}/update`,
          payload
        });
      }
    });
  }
  onEdit  = (record)=>{
    this.save({editVisible:true,record,isCreate:false});
  }
  onDel = (payload)=>{
    this.props.dispatch({
      type:`${ENTITY}/del`,
      payload
    });
  }
  onDelAll = ()=>{
    this.props.dispatch({
      type:`${ENTITY}/delAll`
    });
  }
  handleSearch = ()=>{
    let values = this.searchForm.props.form.getFieldsValue();
    let where = Object.keys(values).reduce((memo,key)=>{
      if(values[key]){
        memo[key] = values[key];
      }
      return memo;
    },{});
    this.props.dispatch({
      type:`${ENTITY}/search`,
      where
    })
  }
  onSetResources = ()=>{ //1.点击按钮，弹出显示出来设置权限的模态窗口
    //我要知道要给哪个角色授权
    let selectedRows = this.props.selectedRows;
    if(selectedRows.length == 1){
      let record = selectedRows[0];
      this.save({resourceModalVisible:true,record,checkedKeys:record.resourceIds});
    }else{
      message.error('能选择并且只能选择一个角色授权');
    }
  }
  setResourceOk = ()=>{//2.保存角色的权限
    this.props.dispatch({
      type:'role/setResources'
    });
  }
  setResourceCancel = ()=>{//取消设置
    this.save({resourceModalVisible:false});
  }
  checkPermissions = (checkedKeys)=>{//当选中了某些权限后，要把选中的权限更新到仓库中
    this.save({checkedKeys});
  }
  onSetUsers = ()=>{
    //我要知道要给哪个角色授权
    let selectedRows = this.props.selectedRows;
    if(selectedRows.length == 1){
      let record = selectedRows[0];
      this.save({userModalVisible:true,record,targetKeys:record.userIds});
    }else{
      message.error('能选择并且只能选择一个角色授权');
    }
  }
  changeUsers = (targetKeys)=>{
    this.save({targetKeys});
  }
  setUserCancel = ()=>{
    this.save({userModalVisible:false});
  }
  setUserOk = ()=>{
    this.props.dispatch({
      type:'role/setUsers'
    });
  }
  render() {
    const columns = [
      {title:'名称',dataIndex:'name',key:'name'},
      {title:'操作',key:'operation',render:(value,record)=>{
         return (
          <Button.Group>
             <Button type="warning" onClick={()=>this.onEdit(record)}>编辑</Button>
             <Popconfirm
                 okText="确认"
                 cancelText="取消"
                 title="请问你是否确定要删除此记录?"
                 onConfirm={()=>this.onDel(record.id)}
             >
               <Button style={{marginLeft:8}} type="danger">删除</Button>
             </Popconfirm>
          </Button.Group>
         )
      }}
    ]
    const {list,pageNum,total,loading,editVisible,
      isCreate,record,selectedRowKeys,resourceModalVisible,
      checkedKeys,resources,userModalVisible,targetKeys,users} = this.props;
    const pagination = {
      current:pageNum,//当前的页码
      pageSize:PAGE_SIZE,//每页的条数
      total,
      showQuickJumper:true,
      showTotal:(total)=>{
        return `共计${total}条`;
      },
      onChange : (pageNum)=>{
        //我需要跳到指定的页码
        // routerRedux.push(`/admin/user?pageNum=1`);
        this.props.dispatch(routerRedux.push({
          pathname:`/admin/${ENTITY}`,
          query:{pageNum}
        }));
      }
    }
    const rowSelection = {
      type:'checkbox',
      selectedRowKeys,
      onChange: (selectedRowKeys,selectedRows)=>{
        this.save({selectedRowKeys,selectedRows});
      }
    }
    const buttonStyle = {style:{marginLeft:10}};
    return (
      <Fragment>
        <Card>
          <SearchForm
           handleSearch={this.handleSearch}
           wrappedComponentRef={inst=>this.searchForm = inst}
          />
        </Card>
        <Card>
          <Button.Group>
            <Button type="warning" onClick={this.onAdd}>添加</Button>
            <Button {...buttonStyle} type="danger" onClick={this.onDelAll}>全部删除</Button>
            <Button {...buttonStyle} type="warning" onClick={this.onSetResources}>设置权限</Button>
            <Button {...buttonStyle} type="warning" onClick={this.onSetUsers}>设置用户</Button>
          </Button.Group>
          <Table
            rowKey={row=>row.id}
            columns={columns}
            dataSource={list}
            loading={loading}
            pagination={pagination}
            rowSelection={rowSelection}
            onRow={
              (record)=>(
                {
                  onClick:()=>{
                    let selectedRowKeys = this.props.selectedRowKeys;
                    let selectedRows = this.props.selectedRows;
                    let index = selectedRowKeys.indexOf(record.id);
                    if(index==-1){
                      selectedRowKeys = [...selectedRowKeys,record.id];
                      selectedRows = [...selectedRows,record];
                    }else{
                      selectedRowKeys = selectedRowKeys.filter(item=>item != record.id);
                      selectedRows = selectedRows.filter(item=>item.id != record.id);
                    }
                    this.save({selectedRowKeys,selectedRows});
                  }
                }
              )
            }
          />
          <EditModal
            wrappedComponentRef={instance => this.editForm = instance}
            visible={editVisible}
            isCreate={isCreate}
            onOk={this.onEditOk}
            onCancel={this.onEditCancel}
            record={record}
          />
          <ResourceModal
           visible={resourceModalVisible}
           onOk={this.setResourceOk}
           onCancel={this.setResourceCancel}
           checkedKeys={checkedKeys}
           onCheck={this.checkPermissions}
           resources={resources}
          />
          <UserModal
           visible={userModalVisible}
           onOk={this.setUserOk}
           onCancel={this.setUserCancel}
           targetKeys={targetKeys}
           onChange={this.changeUsers}
           users={users}
          />
        </Card>
      </Fragment>
    )
  }
}

class UserModal extends Component{
  render(){
    let {visible,onOk,onCancel,targetKeys,onChange,users=[]} = this.props;
    return (
      <Modal
         visible={visible}
         title="给角色选择用户"
         onOk={onOk}
         onCancel={onCancel}
         destroyOnClose
      >
        <Transfer
          dataSource={users}
          targetKeys = {targetKeys}
          titles={["未分配用户","已分配用户"]}
          onChange={onChange}
          render={row=>row.username}
          rowKey={row=>row.id}
        />
      </Modal>
    )
  }
}

class ResourceModal extends Component{
   renderNodes = (resources=[])=>{
    return resources.map(item=>{
      console.log(item);
      if(item.children && item.children.length>0){
        return (
          <Tree.TreeNode key={item.id} title={<span><Icon type={item.icon}/>&nbsp;{item.name}</span>} >
            {this.renderNodes(item.children)}
          </Tree.TreeNode>
        )
      }else{
       return  <Tree.TreeNode key={item.id} title={<span><Icon type={item.icon}/>&nbsp;{item.name}</span>} />
      }
    });
   }
   render(){
     let {visible,onOk,onCancel,checkedKeys,onCheck,resources=[]} = this.props;
     return (
       <Modal
          visible={visible}
          title="给角色授权"
          onOk={onOk}
          onCancel={onCancel}
          destroyOnClose
       >
         <Tree
           checkable
           defaultExpandAll={true}
           checkedKeys = {checkedKeys}
           onCheck={onCheck}
         >
            <Tree.TreeNode title="所有权限" key={0} disabled>
              {this.renderNodes(resources)}
            </Tree.TreeNode>
         </Tree>
       </Modal>
     )
   }
}

@Form.create()
class SearchForm extends Component{
  render(){
    let {form:{getFieldDecorator},handleSearch} = this.props;
    return(
      <Form layout="inline">
          <Form.Item label="名称">
            {
               getFieldDecorator('name',{})(<Input/>)
            }
          </Form.Item>
          <Form.Item>
            <Button onClick={handleSearch} shape="circle" icon="search"></Button>
          </Form.Item>
        </Form>
    )
  }
}

@Form.create()
class EditModal extends Component{
  render(){
    let {form:{getFieldDecorator},visible,isCreate,onOk,onCancel,record} = this.props;
    let formItemLayout = {
      labelCol:{span:4},
      wrapperCol:{span:20}
    }
    return (
      <Modal
         destroyOnClose
         title={isCreate?'增加':'编辑'}
         visible={visible}
         onOk={onOk}
         onCancel={onCancel}
      >
        <Form>
          <Form.Item >
            {
               getFieldDecorator('id',{
                 initialValue:record.id,
               })(<Input  type="hidden"/>)
            }
           </Form.Item>
          <Form.Item label="名称" {...formItemLayout}>
            {
               getFieldDecorator('name',{
                 initialValue:record.username,
                 rules:[{required:true,message:'名称必须输入'}]
               })(<Input/>)
            }
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}